package com.yunwaikeji.gy_tool_library.utils.permission;

import android.content.Context;

import androidx.core.app.ActivityCompat;

import com.yunwaikeji.gy_tool_library.utils.GYUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GYPermissionBuilder {
    private final List<String> permissionList = new ArrayList<>();
    private int requestCode = 0;

    public GYPermissionBuilder addPermissions(List<String> permissionList) {
        this.permissionList.addAll(permissionList);
        return this;
    }

    public GYPermissionBuilder addPermissions(String... permissions) {
        return addPermissions(Arrays.asList(permissions));
    }

    public GYPermissionBuilder setPermissions(List<String> permissionList) {
        this.permissionList.clear();
        return addPermissions(permissionList);
    }

    public GYPermissionBuilder setPermissions(String... permissions) {
        return setPermissions(Arrays.asList(permissions));
    }

    public PermissionAuthorizedResult permissionAuthorizedResult;

    public GYPermissionBuilder setPermissionAuthorizedResult(PermissionAuthorizedResult permissionAuthorizedResult) {
        this.permissionAuthorizedResult = permissionAuthorizedResult;
        return this;
    }

    public GYPermissionBuilder setRequestCode(int requestCode) {
        this.requestCode = requestCode;
        return this;
    }

    public int getRequestCode() {
        return requestCode;
    }

    public void build(Context context) {
        List<String> authorizedList = new ArrayList<>();
        List<String> noList = new ArrayList<>();
        for (String permission : permissionList) {
            if (GYPermissionUtils.isAuthorized(context, permission)) {
                authorizedList.add(permission);
            } else {
                noList.add(permission);
            }
        }
        if (!authorizedList.isEmpty() && permissionAuthorizedResult != null) {
            permissionAuthorizedResult.permissionAuthorized(authorizedList);
        }
        if (!noList.isEmpty()) {
            String[] permissions = noList.toArray(new String[noList.size()]);
            ActivityCompat.requestPermissions(GYUtils.scanForActivity(context), permissions, requestCode);
        }
    }
}
